package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.elm.model.Order;
//import cn.edu.tju.elb.service.OrderService;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.model.OrderDetailet;
//import cn.edu.tju.elm.service.OrderService;
import cn.edu.tju.elm.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.ArrayList;
import java.util.Optional;

@RestController
@RequestMapping("/api/orders")
@Tag(name = "管理订单", description = "对订单进行增删改查")
public class OrderController {
    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @PostMapping(value = "")
    @Operation(summary = "新增订单", description = "用户新增订单")
    public HttpResult<Order> addOrders(@RequestBody Order order) throws Exception{
        try {
            User currentUser = userService.getUserWithAuthorities().get();
            Long userId = currentUser.getId();
            Long businessId=order.getBusiness().getId();
            // 调用服务层从购物车创建订单
            Order createdOrder = orderService.createOrderFromCart(userId, businessId,order);

            return HttpResult.success(createdOrder);

        } catch (Exception e) {
            throw new Exception("创建订单失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取订单详情", description = "根据订单ID获取订单详情")
    public HttpResult getOrderById(@PathVariable Long id) throws Exception{
        List<OrderDetailet> orderDetailets = orderService.findOrderDetailetById(id);

        if (orderDetailets != null && !orderDetailets.isEmpty()) {
            return HttpResult.success(orderDetailets);
        } else {
            return HttpResult.failure(ResultCodeEnum.ORDER_NOT_FOUND);
        }
    }

    @GetMapping("")
    @Operation(summary = "获取用户订单列表", description = "根据用户ID获取订单列表")
    public List<Order> listOrdersByUserId(@RequestParam Long userId) throws Exception{
        List<Order> orders = orderService.findByCustomerId(userId);

        if (orders != null) {
            return orders;
        }
        else {
            return new ArrayList<Order>();
        }
    }



    @GetMapping("/business/{businessId}")
    @Operation(summary = "获取商家订单列表", description = "根据商家ID获取订单列表")
    public HttpResult listOrdersByBusinessId(@PathVariable Long businessId) throws Exception{
        List<Order> orders = orderService.findByBusinessId(businessId);

        if (orders != null && !orders.isEmpty()) {
            return HttpResult.success(orders);
        } else {
            return HttpResult.failure(ResultCodeEnum.ORDER_NOT_FOUND);
        }
    }


    @PutMapping("/{id}/state")
    @Operation(summary = "更新订单状态", description = "根据订单ID更新订单状态")
    public HttpResult<Order> updateOrderState(@PathVariable Long id, @RequestParam Integer orderState) throws Exception {
        try {
            Order updatedOrder = orderService.updateOrderState(id, orderState);
            return HttpResult.success(updatedOrder);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }
}
